<template>
  <div class="todo-container">
    <!-- 头部区域 -->
    <div class="header">
      <h3>我的待办事项</h3>
      <el-button type="primary" @click="handleAdd">新增事项</el-button>
    </div>

    <!-- 时间线区域 -->
    <el-scrollbar
      ref="timeLineScrollRef"
      class="timeline-wrapper"
      @scroll="handleScroll"
    >
      <div style="width: 100%; overflow: hidden">
        <el-timeline v-if="todoList.length">
          <el-timeline-item
            v-for="item in visibleTodos"
            :key="item.id"
            :timestamp="formatTime(item.createdAt)"
            placement="top"
            :color="item.status === 'completed' ? '#67C23A' : '#909399'"
          >
            <div class="todo-content" @click="handleEdit(item)">
              <span :class="{ 'completed-text': item.status === 'completed' }">
                {{ item.content }}
              </span>
              <el-tag
                size="small"
                :type="statusMap[item.status].type"
                effect="plain"
              >
                {{ statusMap[item.status].text }}
              </el-tag>
            </div>
          </el-timeline-item>
        </el-timeline>

        <!-- 加载状态 -->
        <div class="loading-status">
          <span v-show="loading">加载中...</span>
          <span v-show="noMore">没有更多了</span>
        </div>

        <!-- 弹出层 -->
        <div>
          <todo-dialog
            :visible="dialogVisible"
            :isEdit="isEdit"
            :statusMap="statusMap"
            :priorityMap="priorityMap"
            @change="(d) => (dialogVisible = d)"
          ></todo-dialog>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import dayjs from "dayjs";
import TodoDialog from "./TodoDialog.vue";

const timeLineScrollRef = ref(null);
const dialogVisible = ref(false);
const isEdit = ref(false);

// 静态数据生成器
const generateMockData = (count = 10) => {
  return Array.from({ length: count }, (_, i) => ({
    id: Date.now() + i,
    content: `待办事项 ${i + 1}`,
    status: ["pending", "processing", "completed"][i % 3],
    createdAt: dayjs().subtract(i, "hour").toISOString(),
  }));
};

// 响应式数据
const todoList = ref(generateMockData(20)); // 初始20条测试数据
const visibleCount = ref(5); // 每次加载数量
const loading = ref(false);
const noMore = ref(false);

// 显示的数据（模拟分页）
const visibleTodos = computed(
  () => todoList.value.slice(0, visibleCount.value).reverse() // 按时间倒序
);

// 状态管理
const statusMap = {
  pending: { text: "待处理", type: "warning" },
  processing: { text: "进行中", type: "primary" },
  completed: { text: "已完成", type: "success" },
};

// 优先级管理
const priorityMap = {
  low: { text: "低", type: "success" },
  medium: { text: "中", type: "warning" },
  high: { text: "高", type: "danger" },
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm");
};

// 处理新增
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (item) => {
  isEdit.value = true;
  dialogVisible.value = true;
};

// 滚动加载
const handleScroll = () => {
  // 优先使用容器引用获取尺寸（更可靠）
  const container = timeLineScrollRef.value?.wrapRef;
  if (!container) return;

  // 获取精确的容器尺寸
  const { scrollTop, clientHeight, scrollHeight } = container;

  // 触发条件判断
  if (
    scrollHeight - scrollTop - clientHeight < 50 && // 距底部50px阈值
    !loading.value &&
    !noMore.value
  ) {
    console.log("触发加载更多");
    loadMore();
  }
};

// 加载更多（模拟）
const loadMore = () => {
  loading.value = true;
  setTimeout(() => {
    visibleCount.value += 5;
    if (visibleCount.value >= todoList.value.length) {
      noMore.value = true;
    }
    loading.value = false;
  }, 800);
};

// 初始化加载
onMounted(() => {
  todoList.value.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
});
</script>

<style scoped>
.todo-container {
  width: 100%;
  height: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.timeline-wrapper {
  height: calc(100% - 83px);
  padding-right: 15px;
}

.todo-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 8px;
}

.completed-text {
  color: #999;
  text-decoration: line-through;
}

.loading-status {
  padding: 20px 0;
  font-size: 14px;
  color: #666;
  text-align: center;
}

.el-timeline-item__timestamp {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}
</style>
